package com.literature.threeGroup.controller;

import com.literature.threeGroup.pojo.CoverOrder;
import com.literature.threeGroup.pojo.Log;
import com.literature.threeGroup.service.LogsService;
import com.literature.threeGroup.util.PageResult;
import com.literature.threeGroup.util.Result;
import com.literature.threeGroup.util.StatusCode;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author VULCAN
 * @create 2020-01-07 14:31
 * @desc
 **/
@RestController
@CrossOrigin
public class LogsController {

    @Autowired
    private LogsService logService;

    /**
      * @name  模糊
     * @Author VULCAN
     * @Date 2020/1/10 19:59
     */
    @RequestMapping(value = "findlog",method = RequestMethod.POST)
    public List<Log> findlog(@RequestBody Log log){
        List<Log> findall = logService.findlog(log);
        return findall;
    }
    /**
      * @name  分页 模糊
     * @Author VULCAN
     * @Date 2020/1/10 19:59
     */
    @RequestMapping(value = "findlogs/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public Result findlog(@RequestBody Log log, @PathVariable("pageNum") int pageNum , @PathVariable("pageSize") int pageSize){
        PageResult findallpage = logService.findallpage(log,pageNum, pageSize);
        return new Result(true, StatusCode.OK,"查询成功",findallpage) ;
    }
    /**
     * @name  批量删除
     * @Author VULCAN
     * @Date 2020/1/17 9:47
     */
    @RequestMapping(value = "logbulkdel/{id}",method = RequestMethod.GET)
    public String logbulkdel(@PathVariable String id){
        String[] ids = id.split(",");
        System.out.println(ids);
        return logService.logbulkdel(ids);
    }
    /**
     * @name  驳回日志
     * @Author VULCAN
     * @Date 2020/2/2 11:08
     */
    @RequestMapping(value = "logturn/{id}",method = RequestMethod.POST)
    public void logturn(@RequestBody Log log,@PathVariable String id) throws UnknownHostException {
        String[] ids = id.split(",");
        logService.logturn(log,ids);
    }
    //导出单位数据
    @RequestMapping(value = "listOutPutExcel",method = RequestMethod.GET)
    public void export2(HttpServletRequest req, HttpServletResponse resp, String type) throws IOException {
        //列名
        List<String> headers = Arrays.asList("ID", "用户", "类型", "内容", "时间" , "IP");
        List<Map<String, String>> exportDatas = new ArrayList<Map<String, String>>();
        List<Log> orderProductAttrList = logService.findlog(null);


        //将查询结果，存放进列值
        for (Log log : orderProductAttrList) {
            Map<String,String> map=new HashMap<>();
            map.put("ID", log.getLogId());
            map.put("用户", log.getLogName());
            map.put("类型", log.getLogType());
            map.put("内容", log.getLogContent());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 =  format.format(log.getLogDate());
            map.put("时间", format1);
            map.put("IP", log.getLogIp());
            exportDatas.add(map);
        }
        //导出
        exportExcel(req,resp,headers,exportDatas);
    }

    public void exportExcel(HttpServletRequest req, HttpServletResponse resp, List<String> headers, List<Map<String, String>> exportDatas) throws IOException {
        // 创建一个工作薄
        SXSSFWorkbook wb = new SXSSFWorkbook();
        //创建sheet
        Sheet sh = wb.createSheet("日志信息");
        //设置表头字体
        Font headFont = wb.createFont();
        headFont.setFontName("宋体");
        headFont.setColor(HSSFColor.WHITE.index);
        headFont.setFontHeightInPoints((short) 10);// 字体大小
        headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗

        // 设置表头样式
        CellStyle headStyle = wb.createCellStyle();
        headStyle.setFont(headFont);
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        headStyle.setLocked(true);
        headStyle.setWrapText(true);// 自动换行
        headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headStyle.setFillForegroundColor(HSSFColor.GREEN.index);

        // 设置普通单元格字体
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);

        // 设置普通单元格样式
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中
        style.setWrapText(true);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setBorderLeft((short) 1);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        style.setBorderRight((short) 1);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体
        style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色．
        style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色．

        //设置单位格样式为文本
        DataFormat dataFormat = wb.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));

        /**
         * 设置列名
         */
        Row sheetRow = sh.createRow(0);
        Cell cell = null;
        for (int i = 0; i < headers.size(); i++) {
            cell = sheetRow.createCell(i);
            cell.setCellValue(headers.get(i));
            cell.setCellStyle(headStyle);
        }

        /**
         * 设置列值
         */
        int rows = 1;
        for (Map<String, String> data : exportDatas) {
            Row row = sh.createRow(rows++);
            int initCellNo = 0;
            int titleSize = headers.size();
            for (int i = 0; i < titleSize; i++) {
                String key = headers.get(i);
                Object object = data.get(key);
                if (object == null) {
                    row.createCell(initCellNo).setCellValue("");
                } else {
                    row.createCell(initCellNo).setCellValue(String.valueOf(object));
                }
                initCellNo++;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "日志数据" + sdf.format(new Date()) + ".xlsx";
        resp.setContentType("application/octet-stream;charset=utf-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream out = resp.getOutputStream();
        wb.write(out);
        out.close();
    }
    /**
     * @name  rolecount
     * @Author VULCAN
     * @Date 2020/1/28 14:25
     */
    @RequestMapping(value = "logcount",method = RequestMethod.GET)
    public List logcount(){
        return logService.logcount();
    }
    /**
      * @name  日志列表
     * @Author VULCAN
     * @Date 2020/1/28 15:40
     */
    @RequestMapping(value = "findlogs",method = RequestMethod.GET)
    public List<Log> findlogs(){
        List<Log> findall = logService.findlog(null);
        return findall;
    }
}
